package com.zhang.limit;

import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池限流
 */
public class ThreadPoolExecutorLimitDemo {
    public static void main(String[] args) {
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 5, 30, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1), new ThreadPoolExecutor.AbortPolicy());
        // 模拟客户端请求
        for (int i = 0; i < 20; i++) {
            final long num = i;
            poolExecutor.submit(() -> {
                try {
                    System.out.println("当前成功====获取者====:" + num);
                    // 模拟执行时间
                    Thread.sleep(new Random().nextInt(10000));
                    // 打印释放
                    System.out.println("当前成功++++释放者++++:" + num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        poolExecutor.shutdown();
    }
}
